<template>
  <div class="calculator">
    <h2>复利计算器</h2>

    <el-form ref="form" :model="formData" label-position="left" label-width="80px" :rules="rules">
      <el-form-item label="本金" prop="principal">
        <el-input v-model.number="formData.principal" type="number" required></el-input>
      </el-form-item>

      <el-form-item label="年利率（%）" prop="interestRate">
        <el-input v-model.number="formData.interestRate" type="number" step="0.01" required></el-input>
      </el-form-item>

      <el-form-item label="投资期限（年）" prop="years">
        <el-input v-model.number="formData.years" type="number" required></el-input>
      </el-form-item>

      <el-form-item label="每年复利次数" prop="compoundsPerYear">
        <el-input v-model.number="formData.compoundsPerYear" type="number" required></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="calculate">计算复利结果</el-button>
      </el-form-item>

      <p v-if="result" class="result">
        经过 {{ formData.years }} 年，按年利率 {{ formData.interestRate }}%，每年复利 {{ formData.compoundsPerYear }} 次，
        初始本金 {{ formData.principal }} 元将增长至 {{ result.toFixed(2) }} 元。
      </p>
    </el-form>
  </div>
</template>

<script>

export default {
  components: {

  },
  data() {
    return {
      formData: {
        principal: 0, // 本金
        interestRate: 0, // 年利率（百分比）
        years: 0, // 投资期限（年）
        compoundsPerYear: 1, // 每年复利次数
      },
      rules: {
        principal: [{ required: true, message: "请输入本金", trigger: "blur" }],
        interestRate: [{ required: true, message: "请输入年利率", trigger: "blur" }],
        years: [{ required: true, message: "请输入投资期限", trigger: "blur" }],
        compoundsPerYear: [{ required: true, message: "请输入每年复利次数", trigger: "blur" }],
      },
      result: null, // 计算结果
    };
  },
  methods: {
    calculate() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const rate = this.formData.interestRate / 100; // 转换为小数形式的年利率
          const compoundFactor = Math.pow(
            1 + rate / this.formData.compoundsPerYear,
            this.formData.compoundsPerYear * this.formData.years
          );

          this.result = this.formData.principal * compoundFactor;
        } else {
          console.log("校验失败");
        }
      });
    },
  },
};
</script>

<style scoped>
.calculator {
  max-width: 400px;
  margin: 0 auto;
}

.result {
  font-weight: bold;
  margin-top: 1rem;
}
</style>